<template>
  <div style="background: rgba(251, 251, 255)">
    <div class="container" style="padding: 40px 16px 16px 16px">
      <DataOverviewCard :overview="overview" />
      <el-row class="main-layout">
        <el-col :xs="24" :sm="24" :md="16" :lg="16" class="left-col">
          <TodoListCard
            :active-tab="activeTab"
            :todo-list="todoList"
            :pagination="TodoListPagination"
            @tab-change="handleTabChange"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            @process="handleProcess"
          />
          <ContactsCard
            :contact-list="contactList"
            :pagination="contactsPagination"
            :contact-columns="contactColumns"
            @update:name="handleNameUpdate"
            @size-change="handleContactsSizeChange"
            @current-change="handleContactsPageChange"
            :cardType="'HrCard'"
          />
        </el-col>
        <el-col :xs="24" :sm="24" :md="8" :lg="8" class="right-col">
          <RemindersCard :remind-list="remindList" />
          <QuickEntriesCard
            :entries="quickEntries"
            @entry-click="handleEntryClick"
          />
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import DataOverviewCard from "../subcomponent/HR/DataOverviewCard.vue";
import TodoListCard from "../subcomponent/HR/TodoListCard.vue";
import ContactsCard from "../subcomponent/HR/ContactsCard.vue";
import RemindersCard from "../subcomponent/HR/RemindersCard.vue";
import QuickEntriesCard from "../subcomponent/HR/QuickEntriesCard.vue";
import {
  scheduleList,
  DataOverview,
  Myreminder,
} from "@/api/PersonalWorkbench/index.js";
import { pageList } from "@/api/employeeRelations/Archive";

// 数据定义
const overview = reactive({
  entryNum: "",
  icontractNum: "",
  regularizedNum: "",
  transferNum: "",
  dimissionNum: "",
  interviewNum: "",
});

const activeTab = ref("todo");
const searchKey = ref("");
const todoList = ref([]);
const contactList = ref([]);
const remindList = ref([]);
const quickEntries = ref(["转正申请", "调动申请", "离职申请", "我的档案"]);

const contactColumns = [
  { prop: "name", label: "姓名", minWidth: 100 },
  { prop: "name", label: "工号", minWidth: 80 },
  { prop: "sex", label: "性别", minWidth: 100 },
  { prop: "deptName", label: "部门", minWidth: 80 },
  { prop: "jobName", label: "岗位", minWidth: 100 },
  { prop: "phoneNumber", label: "手机号码", minWidth: 80 },
];
// 代办
const TodoListPagination = reactive({
  total: 10,
  page: 1,
  limit: 10,
  pageSizes: [10, 20, 30, 50],
  name: "",
});

const contactsPagination = reactive({
  total: 10,
  page: 1,
  limit: 10,
  pageSizes: [10, 20, 30, 50],
});

const statusMap = {
  todo: 0,
  done: 1,
  completed: 2,
};

const router = useRouter();

// 方法定义
const fetchScheduleList = () => {
  const params = {
    status: statusMap[activeTab.value],
    page: TodoListPagination.page,
    limit: TodoListPagination.limit,
  };

  scheduleList(params)
    .then((res) => {
      todoList.value = res.data.records;
      TodoListPagination.total = res.data.total || 0;
    })
    .catch(console.error);
};

const fetchDataOverview = () => {
  DataOverview().then((res) => {
    if (res.data) {
      Object.assign(overview, res.data);
    }
  });
};

const fetchPageList = () => {
  pageList({
    pageNum: contactsPagination.page,
    pageSize: contactsPagination.limit,
    personName: contactsPagination.name,
  }).then((res) => {
    contactList.value = res.data.records;
    contactsPagination.total = res.data.total || 0;
  });
};

const fetchMyreminder = () => {
  Myreminder().then((res) => {
    remindList.value = res.data;
  });
};

// 事件处理
const handleTabChange = (tab) => {
  activeTab.value = tab;
  TodoListPagination.page = 1;
  fetchScheduleList();
};

// 处理姓名更新
const handleNameUpdate = (name) => {
  contactsPagination.name = name;
  contactsPagination.page = 1; // 搜索时重置到第一页
  fetchPageList();
};

const handleSizeChange = (val) => {
  TodoListPagination.limit = val.limit;
  TodoListPagination.page = 1;
  fetchScheduleList();
};

const handleCurrentChange = (val) => {
  console.log(val);
  TodoListPagination.page = val.page;
  fetchScheduleList();
};

const handleContactsSizeChange = (val) => {
  contactsPagination.limit = val.limit;
  contactsPagination.page = 1;
  fetchPageList();
};

const handleContactsPageChange = (val) => {
  contactsPagination.page = val.page;
  fetchPageList();
};

const handleEntryClick = (entry) => {
  const routeMap = {
    转正申请: "/employeeRelations/regularEmployee",
    调动申请: "/employeeRelations/transferManagement",
    离职申请: "/employeeRelations/separationManagement",
    我的档案: "/archives",
  };

  const targetPath = routeMap[entry];
  if (targetPath) {
    router.push(targetPath);
  }
};

// const handleProcess = (url) => {
//   if (!url) return;
//   window.location.href = /^https?:\/\//i.test(url)
//     ? url
//     : `${import.meta.env.VITE_APP_BASE_API}${url}`;
// };

// 环境判断逻辑
const getEnvBaseUrl = () => {
  // 方案1：根据域名判断（适用于浏览器环境）
  if (
    window.location.hostname === "localhost" ||
    window.location.hostname === "127.0.0.1"
  ) {
    return "http://localhost/";
  }
  if (window.location.hostname === "172.20.19.163") {
    return "http://172.20.19.163:88/";
  }
  // 默认返回测试环境（可根据需要调整）
  return "http://172.20.19.163:88/";
};

// URL处理函数
const handleProcess = (scope) => {
  // 有效性检查
  if (!scope || typeof scope !== "string") {
    console.error("Invalid scope parameter");
    return;
  }
  let finalUrl = scope;
  if (!/^https?:\/\//i.test(scope)) {
    const baseUrl = getEnvBaseUrl();
    finalUrl = `${baseUrl.replace(/\/$/, "")}/${scope.replace(/^\//, "")}`;
  }
  window.location.href = finalUrl;
};
// 初始化
onMounted(() => {
  fetchScheduleList();
  fetchDataOverview();
  fetchPageList();
  fetchMyreminder();
});
</script>

<style scoped lang="scss">
@import "../style/HR.scss";
</style>
